# -*- coding: utf-8 -*-
# @Author : HaleShi
# @Time : 2023-05-23
# @File : 1_r_algorithm.py

import ctypes


def r(data_string):
    def int_overflow(val):
        maxint = 2147483647
        if not -maxint - 1 <= val <= maxint:
            val = (val + (maxint + 1)) % (2 * (maxint + 1)) - maxint - 1
        return val

    def unsigned_right_shitf(n, i):
        # 数字小于0，则转为32位无符号uint
        if n < 0:
            n = ctypes.c_uint32(n).value
        # 正常位移位数是为正数，但是为了兼容js之类的，负数就右移变成左移好了
        if i < 0:
            return -int_overflow(n << abs(i))
        # print(n)
        return int_overflow(n >> i)

    char_list = []
    aae = ['K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'U', 'V',
           'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'e', 'f', 'g', 'h',
           'i', 'j', 'k', 'l', 'm', 'n', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/']
    bArr = data_string.encode('utf-8')
    for i in range(0, len(bArr), 3):
        bArr2 = [None for i in range(4)]
        b2 = 0
        for i2 in range(0, 3):
            i3 = i + i2
            if i3 <= len(bArr) - 1:
                bArr2[i2] = b2 | unsigned_right_shitf((bArr[i3] & 255), ((i2 * 2) + 2))
                b2 = unsigned_right_shitf(((bArr[i3] & 255) << (((2 - i2) * 2) + 2)) & 255, 2)
            else:
                bArr2[i2] = b2
                b2 = 64
        bArr2[3] = b2
        for i4 in range(4):
            if bArr2[i4] <= 63:
                char_list.append(aae[bArr2[i4]])
            else:
                char_list.append("=")

    return "".join(char_list)
